<template>
  <el-form :model="dataForm"
           :rules="dataRule"
           ref="dataForm"
           @keyup.enter.native="dataFormSubmitHandle()"
           status-icon>
    <el-form-item prop="username">
      <el-input v-model.trim="dataForm.username"
                :readonly="isReadonly"
                :placeholder="$t('registered.username')">
        <span slot="prefix"
              class="el-input__icon">
          <svg class="icon-svg"
               aria-hidden="true">
            <use xlink:href="#icon-user"></use>
          </svg>
        </span>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-row :gutter="20">
        <el-col :span="14">
          <el-input v-model.trim="dataForm.captcha"
                    :placeholder="$t('registered.code')">
          </el-input>
        </el-col>
        <el-col :span="10"
                class="login-captcha">
          <el-button type="text"
                     @click="getCode">{{num>0 ? `${num}秒后重新获取`:'获取验证码' }}</el-button>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model.trim="dataForm.password"
                :readonly="isReadonly"
                type="password"
                show-password
                :placeholder="$t('registered.password')">
        <span slot="prefix"
              class="el-input__icon">
          <svg class="icon-svg"
               aria-hidden="true">
            <use xlink:href="#icon-lock"></use>
          </svg>
        </span>
      </el-input>
    </el-form-item>
    <el-form-item prop="confirm">
      <el-input v-model.trim="dataForm.confirm"
                :readonly="isReadonly"
                type="password"
                show-password
                :placeholder="$t('registered.confirm')">
        <span slot="prefix"
              class="el-input__icon">
          <svg class="icon-svg"
               aria-hidden="true">
            <use xlink:href="#icon-lock"></use>
          </svg>
        </span>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary"
                 @click="dataFormSubmitHandle"
                 class="w-percent-100">注册</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import { isMobile } from '@/utils/validate'
import CryptoTool from '@/utils/cryptoTool'
export default {
  data () {
    let password = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length > 16) {
        callback(new Error('请输入8-16位,包括大写字母,小写字母,数字且不能连续升序或降序'))
      } else {
        let pPattern = /^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{8,16}/
        let order = 0 // 顺序
        if (pPattern.test(value)) {
          let arr = value.split('')
          arr.map((item, index) => {
            let num = value.charCodeAt(index) - value.charCodeAt(index + 1)
            if (Math.abs(num) === 1) {
              order += 1
              if (order >= 5) {
                callback(new Error('请输入8-16位,包括大写字母,小写字母,数字且不能连续升序或降序'))
              }
            } else {
              order = 0
            }
          })
          callback()
        } else {
          callback(new Error('请输入8-16位,包括大写字母,小写字母,数字且不能连续升序或降序'))
        }
      }
    }
    let username = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else if (value.length > 16) {
        callback(new Error('请输入4-16位字母,数字做为用户名'))
      } else {
        let pPattern = /^[a-zA-Z0-9]{4,16}$/g
        if (pPattern.test(value)) {
          callback()
        } else {
          callback(new Error('请输入4-16位字母,数字做为用户名'))
        }
      }
    }
    return {
      scale: {
        transform: `scale(1)`
      },
      num: 0,
      isReadonly: true,
      i18nMessages: messages,
      captchaPath: '',
      timer: '',
      str: '混淆字段',
      dataForm: {
        username: '',
        captcha: '',
        password: '',
        confirm: ''
      },
      dataRule: {
        username: [
          { required: true, validator: username, trigger: 'change' }
        ],
        password: [
          { required: true, validator: password, trigger: 'change' }
        ],
        confirm: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        company: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        tel: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        captcha: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ]
      }
    }
  },
  mounted () {
    let userInfo = sessionStorage.getItem('userInfo')
    if (userInfo) {
      userInfo = JSON.parse(userInfo)
      this.dataForm = Object.assign({}, {}, {
        username: userInfo.user,
        password: CryptoTool.decrypt(userInfo.pwd),
        confirm: CryptoTool.decrypt(userInfo.pwd)
      })
    }
    let self = this
    let width = document.documentElement.offsetWidth
    let num = width * 0.0005208
    if (num > 1) {
      num = 1
    }
    self.scale = {
      transform: `scale(${num})`
    }
    setTimeout(() => {
      this.isReadonly = false
    }, 500)

    let timeNum = window.sessionStorage.getItem('num')
    if (!timeNum) {
      return
    }
    timeNum = CryptoTool.decrypt(timeNum)
    timeNum = timeNum.replace(this.str, '')
    const timer = localStorage.getItem('timer')
    clearInterval(parseInt(timer))
    if (timeNum > 0) {
      this.timer = setInterval(() => {
        let timeNum = CryptoTool.decrypt(window.sessionStorage.getItem('num'))
        timeNum = timeNum.replace(this.str, '')
        timeNum--
        this.num = timeNum
        window.sessionStorage.setItem('num', CryptoTool.encrypt(timeNum.toString() + this.str))
        if (timeNum <= 0) {
          window.clearInterval(this.timer)
        }
      }, 1000)
      localStorage.setItem('timer', this.timer)
    }
  },
  methods: {
    // 获取验证码
    getCode () {
      let time = window.sessionStorage.getItem('time')
      if (time) {
        time = CryptoTool.decrypt(time)
      }
      if (!isMobile(this.dataForm.username)) {
        this.$message.warning('请填写正确的手机号')
        return
      }
      let nowTime = new Date().getTime()
      if (nowTime - time > 60000) {
        let tempNum = 60
        window.sessionStorage.setItem('time', CryptoTool.encrypt(nowTime.toString()))
        window.sessionStorage.setItem('num', CryptoTool.encrypt(tempNum.toString()))
        // 倒计时
        this.timer = setInterval(() => {
          let num = CryptoTool.decrypt(window.sessionStorage.getItem('num'))
          num = num.replace(this.str, '')
          num--
          this.num = num
          window.sessionStorage.setItem('num', CryptoTool.encrypt(num.toString() + this.str))
          if (num <= 0) {
            window.clearInterval(this.timer)
          }
        }, 1000)
        localStorage.setItem('timer', this.timer)

        // 获取短信
        this.$http.get(`/telcaptcha?phone=${this.dataForm.username}&scenarioType=${'registration'}`).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success('短信已发出，请注意接收')
        }).catch(() => { })
      } else {
        this.$message.warning('操作过于频繁，请稍后再试')
      }
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          return false
        }

        if (this.dataForm.password !== this.dataForm.confirm) {
          this.$message.error('两次的密码不一致')
          return false
        }
        let query = {
          user: this.dataForm.username,
          pwd: CryptoTool.encrypt(this.dataForm.password)
        }
        sessionStorage.setItem('userInfo', JSON.stringify(query))
        this.$router.push(
          {
            name: 'registered-next',
            params: query
          })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style lang="scss">
</style>
